import wepy from 'wepy'
import constant from '../utils/constant.utils'

let requestInfo = {
  baseParams: {},
  successCode: [],
  successCallBack: null,
  errorCallBack: null
}
/**
 * set http base info
 * @param {*}
 *  baseParams carry request params
 *  successCode
 *  successBusinessCode
 *  successCallBack
 *  errorCallBack
 */
const setHttpRequest = ({
  baseParams = {},
  successCode = [],
  successBusinessCode = [],
  successCallBack = null,
  errorCallBack = null
} = {}) => {
  Object.assign(requestInfo, {
    baseParams,
    successCode,
    successBusinessCode,
    successCallBack,
    errorCallBack
  })
}

/**
 * 发送请求
 * @param {successCode} // 允许走resolve的code，由业务方决定
 */
const request = function(path, {successCode = [], data = {}, header = {}, method = 'GET', dataType = 'json', responseType = 'text', complete = ''} = {}) {
  // 默认参数：platform平台类型、bizType业务类型、enterpriseId企业ID
  let globalData = wepy.$instance.globalData
  let url = `${path}?platform=${constant.platform}&bizType=${constant.bizType}&enterpriseId=${globalData.enterpriseId}&channel=${constant.bizType}&channelId=${globalData.appId}`
  let requestCookie = getRequestCookie({ header })
  return new Promise((resolve, reject) => {
    wepy
      .request({
        url,
        data: Object.assign({}, requestInfo.baseParams, data),
        header: Object.assign({}, header, {
          cookie: Object.entries(requestCookie)
            .reduce((acc, item) => [...acc, ...Array.of(item.join('='))], [])
            .join('; ')
        }),
        method,
        dataType,
        responseType
      })
      .then(response => {
        // judge http code
        if (Number(response.statusCode) !== 200) {
          return reject(response)
        }

        if (
          [
           ...requestInfo.successCode,
           ...requestInfo.successBusinessCode,
           ...successCode
          ].includes(Number(response.data.ecode))
        ) {
          requestInfo.successCallBack &&
            typeof requestInfo.successCallBack === 'function' &&
            requestInfo.successCallBack(response.data)
            let resolveCode = [ ...requestInfo.successCode, ...successCode ]
            resolveCode.includes(Number(response.data.ecode)) &&
            resolve(response.data)
        } else {
          requestInfo.errorCallBack &&
            typeof requestInfo.errorCallBack === 'function' &&
            requestInfo.errorCallBack(response)
          reject(response)
        }
      })
  })
}

const getRequestCookie = ({ header = {} } = {}) => {
  let requestCooike = !!Object.prototype.hasOwnProperty.call(header, 'cookie')
    ? Object.assign({}, header['cookie'])
    : {}
  let loginSessionKey = wx.getStorageSync('LOGIN_COOKIE_KEY')
  let loginSession = wx.getStorageSync('LOGIN_COOKIE')
  let sid = {}
  loginSessionKey && loginSession && (sid[loginSessionKey] = loginSession)
  if (!!loginSession) Object.assign(requestCooike, sid)
  return requestCooike
}

export { request, setHttpRequest }
